from datetime import datetime
import re
from rest_framework import serializers
from .models import DjChefWallet, DjWalletTransaction, DjWithdrawal, DjChefBankCard

class ChefWalletSerializer(serializers.ModelSerializer):
    class Meta:
        model = DjChefWallet
        fields = ['id',
            'balance', 'frozen_amount', 'total_earned', 
            'total_withdrawn', 'daily_withdraw_limit',
            'min_withdraw_amount', 'withdraw_count_today'
        ]
        read_only_fields = fields


class DjWithdrawalSerializer(serializers.ModelSerializer):
    """提现记录序列化器，返回前端所需的关键信息"""
    class Meta:
        model = DjWithdrawal
        fields = [
            'id', 'amount', 'fee', 'method', 'status',
            'requested_at', 'processed_at', 'failure_reason'
            , 'account_number'  # 银行卡信息（脱敏）
        ]
        read_only_fields = fields

class ChefWithdrawalReviewSerializer(serializers.ModelSerializer):
    class Meta:
        model = DjWithdrawal
        fields = ['status', 'failure_reason']
        extra_kwargs = {
            'failure_reason': {'required': False}
        }
        
class ChefWithdrawalSerializer(serializers.ModelSerializer):
    # 新增：显示银行卡号（从关联的bank_card获取）
    card_number = serializers.SerializerMethodField(read_only=True)
    # 可选项：显示银行名称
    bank_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = DjWithdrawal
        fields = [
            'id', 'amount', 'method', 'status',
            'bank_card', 'card_number', 'bank_name', 'requested_at'
        ]
        extra_kwargs = {
            'bank_card': {'write_only': True},  # 写入时传ID，展示时用卡号
            'status': {'read_only': True},      # 状态由后端控制
            'requested_at': {'read_only': True} # 时间由后端生成
        }

    def get_card_number(self, obj):
        """从关联的银行卡获取卡号（可格式化显示）"""
        if obj.bank_card and obj.bank_card.card_number:
            # 示例：只显示后四位，中间用*代替
            return f"**** **** **** {obj.bank_card.card_number[-4:]}"
        return "未关联银行卡"

    def get_bank_name(self, obj):
        """获取银行名称用于展示"""
        if obj.bank_card:
            return obj.bank_card.bank_name  # 假设DjChefBankCard有bank_name字段
        return ""

    def validate_amount(self, value):
        # 从上下文获取厨师信息（而非直接获取wallet）
        chef = self.context.get('chef')
        if not chef:
            raise serializers.ValidationError("未找到厨师信息")

        # 从厨师信息中获取钱包
        wallet = chef.payment_wallet
        if not wallet:
            raise serializers.ValidationError("未找到关联的钱包")

        # 验证金额是否符合要求（假设钱包有balance字段）
        if value <= 0:
            raise serializers.ValidationError("提现金额必须大于0")
        
        if value > wallet.balance:
            raise serializers.ValidationError(f"提现金额超过可用余额，当前余额: {wallet.balance}")
        
        return value
    
class BankCardSerializer(serializers.ModelSerializer):
    class Meta:
        model = DjChefBankCard
        fields = [
            'id', 'bank_name', 'bank_code', 'card_holder',
            'last_four', 'card_type', 'is_default'
        ]
        read_only_fields = fields

class BankCardCreateSerializer(serializers.ModelSerializer):
    bank_code = serializers.CharField(
        max_length=10,
        help_text="银行代码，如ICBC、CCB等"
    )
    card_number = serializers.CharField(
        max_length=19,
        min_length=16,
        write_only=True,
        help_text="16-19位银行卡号"
    )
    card_holder = serializers.CharField(
        max_length=50,
        help_text="持卡人姓名"
    )
    expire_date = serializers.CharField(
        max_length=5,
        min_length=5,
        write_only=True,
        help_text="有效期，格式MM/YY"
    )

    class Meta:
        model = DjChefBankCard
        fields = [
            'bank_code', 'card_number','card_type',
            'card_holder', 'expire_date'
        ]
        extra_kwargs = {
            'card_number': {'write_only': True},
            'expire_date': {'write_only': True}
        }

    def validate_card_number(self, value):
        """卡号验证"""
        value = value.replace(' ', '')
        if not value.isdigit():
            raise serializers.ValidationError("卡号必须为数字")
        if len(value) < 16 or len(value) > 19:
            raise serializers.ValidationError("卡号长度应为16-19位")
        return value

    def validate_expire_date(self, value):
        """有效期验证"""
        if not re.match(r'^(0[1-9]|1[0-2])\/?([0-9]{2})$', value):
            raise serializers.ValidationError("有效期格式应为MM/YY")
        
        month, year = map(int, value.split('/'))
        expire_date = datetime(2000 + year, month, 1).date()
        if expire_date < datetime.now().date():
            raise serializers.ValidationError("卡片已过期")
        return value

    def validate_bank_code(self, value):
        """简单的银行代码验证"""
        valid_codes = ['ICBC', 'CCB', 'BOC', 'CMB', 'ABC', 'BOCOM', 'SPDB', 'CMBC', 'CIB', 'PAB']
        if value not in valid_codes:
            raise serializers.ValidationError("不支持的银行代码")
        return value # 只存储末四位

class WithdrawalSerializer(serializers.ModelSerializer):
    class Meta:
        model = DjWithdrawal
        fields = [
            'id', 'amount', 'method', 'status',
            'requested_at', 'processed_at'
        ]
        read_only_fields = ['status', 'requested_at', 'processed_at']

class DjChefBankCardSerializer(serializers.ModelSerializer):
    """银行卡信息序列化器"""
    class Meta:
        model = DjChefBankCard
        fields = [
            'id', 'bank_name', 'bank_code', 'last_four', 
            'card_type', 'card_holder', 'is_default'
        ]
class DjWalletTransactionSerializer(serializers.ModelSerializer):
    """钱包交易流水序列化器，用于展示收入相关记录"""
    # 交易类型中文显示
    transaction_type_display = serializers.CharField(source='get_transaction_type_display', read_only=True)
    # 关联订单号（若有）
    order_number = serializers.SerializerMethodField(read_only=True)
    # 关联提现ID（若有）
    withdrawal_id = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = DjWalletTransaction
        fields = [
            'id', 'transaction_type', 'transaction_type_display',
            'amount', 'transaction_id', 'note', 'created_at',
            'order_number', 'withdrawal_id'
        ]
        read_only_fields = fields  # 所有字段均为只读

    def get_order_number(self, obj):
        """获取关联订单的编号（若存在）"""
        if obj.related_order:
            return obj.related_order.order_number  # 假设Order模型有order_number字段
        return None

    def get_withdrawal_id(self, obj):
        """获取关联提现记录的ID（若存在）"""
        if obj.related_withdrawal:
            return obj.related_withdrawal.id
        return None
class WithdrawalInfoSerializer(serializers.Serializer):
    """提现信息序列化器"""
    #id = erializers.DecimalField(max_digits=12, decimal_places=2)
    balance = serializers.DecimalField(max_digits=12, decimal_places=2)
    available_balance = serializers.DecimalField(max_digits=12, decimal_places=2)
    daily_withdraw_limit = serializers.DecimalField(max_digits=12, decimal_places=2)
    min_withdraw_amount = serializers.DecimalField(max_digits=12, decimal_places=2)
    withdraw_fee_rate = serializers.DecimalField(max_digits=5, decimal_places=2)
    default_card = DjChefBankCardSerializer(read_only=True)
    can_withdraw = serializers.BooleanField()  # 是否可提现